package com.tbm.console.proj.json;

import com.alibaba.fastjson.JSONArray;
import com.tbm.console.base.controller.BaseController;
import com.tbm.console.common.constant.ConsoleConstant;
import com.tbm.console.common.constant.InsUpdDelFlagConstant;
import com.tbm.console.proj.entity.SystemButton;
import com.tbm.console.proj.entity.SystemMenu;
import com.tbm.console.proj.entity.SystemRole;
import com.tbm.console.proj.modal.SystemMenuParam;
import com.tbm.console.proj.service.SystemButtonService;
import com.tbm.console.proj.service.SystemMenuService;
import com.tbm.console.util.PageData;
import com.tbm.console.util.RightsHelper;
import lombok.extern.slf4j.Slf4j;
import org.omg.PortableServer.POA;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.Table;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
public class SystemMenuJson extends BaseController {

    @Autowired
    private SystemMenuService systemMenuService;

    @Autowired
    private SystemButtonService systemButtonService;


    /**
     * 后台分页
     * @return
     */
    @RequestMapping("/menu-list-json")
    public Map<String,Object> roleListJson(){
        PageData pageData = this.getPageData();
        Integer page = Integer.valueOf(pageData.get("page").toString().equals("0")?"1":pageData.get("page").toString());
        Integer rows = Integer.valueOf(pageData.get("rows").toString());
        PageData pd = new PageData();
        pd.put("parentId", "0");
        pd.put("deleteFlag", InsUpdDelFlagConstant.DELETE_FLAG_N);
        Long count = systemMenuService.count(pd);
        List<SystemMenu> parentMenus = systemMenuService.findAll(pd,page-1, rows);
        List<PageData> pdList = new ArrayList<>();

        PageData first = new PageData();
        first.put("id", 0);
        first.put("menuName", "系统页面树形结构图");
        first.put("parentId", "-3");
        pdList.add(first);
        for(SystemMenu pMenu:parentMenus){
            PageData menu = new PageData();
            menu.put("id", pMenu.getId());
            menu.put("menuName", pMenu.getMenuName());
            menu.put("menuURL", pMenu.getMenuURL());
            menu.put("menuIcon", pMenu.getMenuIcon());
            menu.put("_parentId", pMenu.getParentId());
            menu.put("parentId", pMenu.getParentId());
            menu.put("state", "closed");
            pdList.add(menu);
            pd.put("parentId", pMenu.getId());
            pd.put("deleteFlag", InsUpdDelFlagConstant.DELETE_FLAG_N);
            List<SystemMenu> sonMenus = systemMenuService.findAll(pd);
            for(SystemMenu sMenu: sonMenus){
                PageData son = new PageData();
                son.put("id", sMenu.getId()+1000);
                son.put("menuName", sMenu.getMenuName());
                son.put("menuURL", sMenu.getMenuURL());
                son.put("_parentId", sMenu.getParentId());
                son.put("parentId", sMenu.getParentId());
                son.put("iconCls","icon-node");
                son.put("state", "closed");
                pdList.add(son);
                pd.put("menuID", sMenu.getId());
                pd.put("deleteFlag", InsUpdDelFlagConstant.DELETE_FLAG_N);
                List<SystemButton> all = systemButtonService.findAll(pd);
                for(SystemButton sb:all){
                    PageData button = new PageData();
                    button.put("id", sb.getId()+2000);
                    button.put("menuName", sb.getButtonName());
                    button.put("_parentId", sMenu.getId()+1000);
                    button.put("menuURL", sb.getIconCls());
                    button.put("iconCls", sb.getIconCls());
                    button.put("parentId", "-1");
                    pdList.add(button);
                }
            }
        }
        PageData result = new PageData();
        result.put("total", count);
        result.put("rows", pdList);
        return result;
    }

    @RequestMapping("/menu-tree-list")
    public Map<String,Object> menuTreeList(){

        //获取所有Menu
        List<PageData> result = new ArrayList<>();
        PageData root = new PageData();
        root.put("id", 9999);
        root.put("menuName", "菜单管理树根");
        root.put("remark", "root");
        root.put("iconCls", "icon-pencil");
        result.add(root);
        List<SystemMenu> all = systemMenuService.findAll();
        for(SystemMenu systemMenu : all){
            //先保存parent=0
            if(systemMenu.getParentId().equals("0")){
                PageData pageData = new PageData();
                pageData.put("id", systemMenu.getId());
                pageData.put("menuName", systemMenu.getMenuName());
                pageData.put("remark", "parent-menu");
                pageData.put("state", "closed");
                pageData.put("iconCls", "icon-edit_remove");
                pageData.put("_parentId", 9999);
                result.add(pageData);
                for(SystemMenu sonSystemMenu : all){
                    //此parent对应的sonList
                    if(sonSystemMenu.getParentId().equals(String.valueOf(systemMenu.getId()))){
                        PageData sonPageData = new PageData();
                        sonPageData.put("id",sonSystemMenu.getId());
                        sonPageData.put("menuName", sonSystemMenu.getMenuName());
                        sonPageData.put("remark", "son-menu");
                        sonPageData.put("state", "closed");
                        sonPageData.put("iconCls", ".icon-new");
                        sonPageData.put("_parentId", systemMenu.getId());
                        result.add(sonPageData);

                        //此页面所对应的按钮
                        PageData paramPageData = new PageData();
                        paramPageData.put("menuID", sonSystemMenu.getId());
                        List<SystemButton> buttons = systemButtonService.findAll(paramPageData);
                        for(SystemButton systemButton:buttons){
                            PageData buttonPageData = new PageData();
                            buttonPageData.put("id", 200 + systemButton.getId());
                            buttonPageData.put("menuName", systemButton.getButtonName());
                            buttonPageData.put("remark", "button");
                            buttonPageData.put("_parentId", sonSystemMenu.getId());
                            buttonPageData.put("iconCls", systemButton.getIconCls());
                            result.add(buttonPageData);
                        }
                    }
                }
            }

        }

        PageData pageData = new PageData();
        pageData.put("total", 14);
        pageData.put("rows", result);
        return pageData;

    }

    @RequestMapping("/menu-list")
    public Object adminGetRoleList(){

        //menu-list
        List<PageData> pageDataList = new ArrayList<PageData>();
        List<SystemMenu> menuList = systemMenuService.findAll();

        //获取
        for(SystemMenu roleEntity : menuList){
            String parentId = roleEntity.getParentId();
            if("0".equals(parentId)){
                for(SystemMenu systemMenu : menuList){
                    if(systemMenu.getParentId().equals(String.valueOf(roleEntity.getId()))){
                        PageData pd = new PageData();
                        pd.put("value",systemMenu.getId());
                        pd.put("text",systemMenu.getMenuName());
                        pd.put("group", roleEntity.getMenuName());
                        pageDataList.add(pd);
                    }
                }
            }
        }
        return JSONArray.toJSONString(pageDataList);
    }

    @RequestMapping("/menu-save/{id}/{parentId}")
    public Map<String,Object> menuSave(@PathVariable("id") String id,@PathVariable("parentId") String parentId){
        PageData pageData = this.getPageData();
        SystemMenu systemMenu = systemMenuService.findById(Integer.valueOf(id));
        if(null!=pageData.get("menu_name")&&!"".equals(pageData.get("menu_name").toString())){
            systemMenu.setMenuName(pageData.getString("menu_name"));
        }
        if(null!=pageData.get("menu_icon")&&!"".equals(pageData.get("menu_icon").toString())){
            systemMenu.setMenuIcon(pageData.getString("menu_icon"));
        }
        if(null!=pageData.get("menu_url")&&!"".equals(pageData.get("menu_url").toString())){
            systemMenu.setMenuURL(pageData.getString("menu_url"));
        }
        if(null!=pageData.get("menu_parent")&&!"".equals(pageData.get("menu_parent").toString())){
            systemMenu.setParentId(pageData.getString("menu_parent"));
        }
        //-1表示新增父页面
        if(-1==Integer.valueOf(id)){
            systemMenu.setParentId("0");
            systemMenu.setMenuURL("#");
        }
        //-2表示新增子页面
        if(-2==Integer.valueOf(id)){
            systemMenu.setParentId(parentId);
        }
        SystemMenu save = systemMenuService.save(systemMenu);
        Map<String, Object> map = new HashMap<>();
        map.put("result", "success");
        map.put("parentId", save.getParentId());
        return map;
    }

    @RequestMapping("/menu-delete")
    public String menuDelete(){
        PageData pageData = this.getPageData();
        String idStr = pageData.get("id").toString();
        try{
            Integer id = Integer.valueOf(idStr);
            SystemMenu byId = systemMenuService.findById(id);
            byId.setDeleteFlag(InsUpdDelFlagConstant.DELETE_FLAG_Y);
            SystemMenu save = systemMenuService.save(byId);
            return save.getParentId();
        }catch (Exception e){

        }
        return "";
    }

    @RequestMapping(value = "/menu-key-value")
    public Object constantsByType(){
        //先查redis，如果缓存有，直接返回，如果没有查询数据库，在将查询出来的结果存储到缓存中
        List<PageData> pageList = new ArrayList<>();
        PageData pageData = new PageData();
        pageData.put("parentId", "0");
        List<SystemMenu> all = systemMenuService.findAll(pageData);
        for(SystemMenu menu : all){
            PageData pd = new PageData();
            pd.put("key",menu.getMenuName());
            pd.put("value",menu.getId());
            pageList.add(pd);
        }
        return pageList;
    }

    @RequestMapping(value = "/menu-name/{id}")
    public Object menuNameById(@PathVariable("id") String id) {
        try{
            Integer idInteger = Integer.valueOf(id);
            //本应该从redis读取
            SystemMenu byId = systemMenuService.findById(idInteger);
            return byId.getMenuName();
        }catch (java.lang.NumberFormatException e){
            return "";
        }
    }
}
